<template>
  <div class="map-view-container">
    <div class="map-tools">
      <el-radio-group v-model="viewMode" size="small">
        <el-radio-button label="all">全部点位</el-radio-button>
        <el-radio-button label="latest">最新点位</el-radio-button>
      </el-radio-group>
      
      <el-select 
        v-model="selectedLocator" 
        placeholder="选择定位器" 
        size="small"
        clearable
        @change="handleLocatorChange"
      >
        <el-option 
          v-for="item in locatorOptions" 
          :key="item.value" 
          :label="item.label" 
          :value="item.value"
        />
      </el-select>
    </div>
    
    <div id="mapContainer" class="map-container"></div>
    
    <div class="log-list" v-if="viewMode === 'all'">
      <el-table
        :data="logList"
        height="200"
        size="mini"
        @row-click="handleRowClick"
      >
        <el-table-column label="定位器" prop="locatorCode" width="100" />
        <el-table-column label="上传时间" width="150">
          <template slot-scope="scope">
            {{ parseTime(scope.row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column label="位置">
          <template slot-scope="scope">
            {{ scope.row.uploadAddress || `${scope.row.latitude}, ${scope.row.longitude}` }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { getLocatorOptions } from "@/api/pack/locator";

export default {
  name: "MapView",
  props: {
    logList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      map: null,
      markers: [],
      viewMode: 'all',
      selectedLocator: null,
      locatorOptions: []
    };
  },
  computed: {
    // 根据筛选条件过滤日志列表
    filteredLogList() {
      if (!this.logList || this.logList.length === 0) {
        return [];
      }
      
      let filteredList = [...this.logList];
      
      // 如果选择了定位器，则按定位器筛选
      if (this.selectedLocator) {
        filteredList = filteredList.filter(log => log.locatorId === this.selectedLocator);
      }
      
      // 如果是最新点位模式，则按定位器分组并只保留每组最新的点位
      if (this.viewMode === 'latest') {
        const latestLogs = {};
        filteredList.forEach(log => {
          const locatorId = log.locatorId;
          if (!latestLogs[locatorId] || new Date(log.uploadTime) > new Date(latestLogs[locatorId].uploadTime)) {
            latestLogs[locatorId] = log;
          }
        });
        filteredList = Object.values(latestLogs);
      }
      
      return filteredList;
    }
  },
  mounted() {
    this.initMap();
    this.initLocatorOptions();
  },
  methods: {
    // 初始化地图
    initMap() {
      // 加载高德地图脚本（如果未加载）
      this.loadMapScript().then(() => {
        // 创建地图实例
        this.map = new AMap.Map('mapContainer', {
          zoom: 10,
          center: [116.397428, 39.90923] // 默认中心点
        });
        
        // 添加地图控件
        this.map.plugin(['AMap.ToolBar', 'AMap.Scale'], () => {
          this.map.addControl(new AMap.ToolBar());
          this.map.addControl(new AMap.Scale());
        });
        
        // 添加标记点
        this.addMarkers();
      });
    },
    
    // 加载高德地图脚本
    loadMapScript() {
      // 使用map-utils.js中的loadAMapScript方法
      return import('@/components/MapContainer/map-utils').then(module => {
        return module.loadAMapScript();
      });
    },
    
    // 添加标记点
    addMarkers() {
      // 清除现有标记点
      if (this.markers.length > 0) {
        this.map.remove(this.markers);
        this.markers = [];
      }
      
      // 如果没有日志数据，则返回
      if (!this.filteredLogList || this.filteredLogList.length === 0) {
        return;
      }
      
      // 创建标记点
      const bounds = new AMap.Bounds();
      this.filteredLogList.forEach(log => {
        // 检查是否有经纬度数据
        if (!log.latitude || !log.longitude) {
          return;
        }
        
        // 创建标记点
        const position = [log.longitude, log.latitude];
        const marker = new AMap.Marker({
          position,
          title: `${log.locatorCode} - ${this.parseTime(log.uploadTime)}`,
          extData: log
        });
        
        // 添加点击事件
        marker.on('click', () => {
          this.showInfoWindow(marker);
        });
        
        // 添加到地图
        this.markers.push(marker);
        
        // 扩展边界
        bounds.extend(position);
      });
      
      // 添加标记点到地图
      this.map.add(this.markers);
      
      // 调整地图视野
      if (this.markers.length > 0) {
        this.map.setFitView(this.markers);
      }
    },
    
    // 显示信息窗口
    showInfoWindow(marker) {
      const log = marker.getExtData();
      const content = `
        <div class="info-window">
          <h4>${log.locatorCode}</h4>
          <p>上传时间：${this.parseTime(log.uploadTime)}</p>
          <p>位置：${log.uploadAddress || '未知地址'}</p>
          <p>经纬度：${log.latitude}, ${log.longitude}</p>
          <p>电量：${log.batteryLevel}%</p>
          <p>温度：${log.temperature}°C</p>
          <p>湿度：${log.humidity}%</p>
          <p>震动等级：${this.getShockLevelText(log.shockLevel)}</p>
        </div>
      `;
      
      // 创建信息窗口
      const infoWindow = new AMap.InfoWindow({
        content,
        offset: new AMap.Pixel(0, -30)
      });
      
      // 打开信息窗口
      infoWindow.open(this.map, marker.getPosition());
    },
    
    // 初始化定位器选项
    initLocatorOptions() {
      // 使用API获取定位器选项列表
      getLocatorOptions().then(response => {
        this.locatorOptions = response.data || [];
      }).catch(() => {
        // 如果API调用失败，回退到从日志列表中提取定位器信息
        const locatorMap = {};
        this.logList.forEach(log => {
          if (log.locatorId && log.locatorCode) {
            locatorMap[log.locatorId] = log.locatorCode;
          }
        });
        
        // 转换为选项格式
        this.locatorOptions = Object.entries(locatorMap).map(([id, code]) => ({
          value: parseInt(id),
          label: code
        }));
      });
    },
    
    // 处理定位器选择变更
    handleLocatorChange() {
      this.addMarkers();
    },
    
    // 处理表格行点击
    handleRowClick(row) {
      // 找到对应的标记点
      const marker = this.markers.find(m => m.getExtData().logId === row.logId);
      if (marker) {
        // 居中地图到标记点位置
        this.map.setCenter(marker.getPosition());
        // 显示信息窗口
        this.showInfoWindow(marker);
      }
    },
    
    // 获取震动等级文本
    getShockLevelText(level) {
      const texts = ['', '轻微', '一般', '中等', '强烈', '剧烈'];
      return texts[level] || '未知';
    }
  },
  watch: {
    // 监听视图模式变更
    viewMode() {
      this.addMarkers();
    },
    
    // 监听日志列表变更
    logList: {
      handler() {
        this.initLocatorOptions();
        this.addMarkers();
      },
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.map-view-container {
  display: flex;
  flex-direction: column;
  height: 600px;
  
  .map-tools {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 10px;
  }
  
  .map-container {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .log-list {
    margin-top: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
}

:deep(.info-window) {
  padding: 5px;
  max-width: 300px;
  
  h4 {
    margin: 0 0 5px 0;
    color: #409eff;
  }
  
  p {
    margin: 3px 0;
    font-size: 12px;
  }
}
</style> 